<template>
  <div class="student-list">
    <div class="header">
      <h2>学生列表</h2>
      <el-button type="primary" @click="handleAdd" v-if="isAdmin">添加学生</el-button>
    </div>

    <el-table :data="students" style="width: 100%" v-loading="loading">
      <el-table-column prop="studentNumber" label="学号" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          {{ row.gender === 'MALE' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="birthDate" label="出生日期" width="120" />
      <el-table-column prop="className" label="班级" width="120" />
      <el-table-column prop="major" label="专业" width="150" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const students = ref([])
const loading = ref(false)

const user = computed(() => {
  const userStr = localStorage.getItem('user')
  return userStr ? JSON.parse(userStr) : null
})

const isAdmin = computed(() => {
  return user.value?.role === 'ADMIN'
})

const fetchStudents = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:8080/api/students')
    students.value = response.data
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error('Error fetching students:', error)
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  router.push('/students/add')
}

const handleEdit = (row) => {
  router.push(`/students/edit/${row.id}`)
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除学生 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.delete(`http://localhost:8080/api/students/${row.id}`)
      ElMessage.success('删除成功')
      fetchStudents()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('Error deleting student:', error)
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.student-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}
</style> 